<template>
  <view class="com-order-dialog" v-if="show">
    <u-row gutter="0" customStyle="width:750rpx;align-items:normal;">
      <u-col span="4">
        <view class="col-layout">
          <view class="close" @click="emitCancel">
            <u-icon name="close" size="15rpx" bold></u-icon>
          </view>

          <!-- 支付方式选择 -->

          <view class="title"> <text>待收款</text></view>
          <view class="price-txt">
            <text>{{ info.money }}</text>
          </view>

          <view class="merber-info-list mt-10rpx">
            <view class="show-total-price">
              <text>合计金额</text>
              <text class="price-txt">{{ info.total }}</text>
            </view>
            <view class="show-total-price" v-if="cardInfo.membershipCardType">
              <text>卡片类型</text>
              <text class="font-bold">{{ cardInfo.membershipCardType == 1 ? "会员卡" : "套餐卡" }}</text>
            </view>
            <template v-if="cardInfo.membershipCardType == 1">
              <view class="show-total-price">
                <text>会员等级</text>
                <text class="font-bold">{{ memberInfo.membershipLevelName || "-" }}</text>
              </view>
              <view class="show-total-price" v-if="['card', 'face', ''].includes(currType)">
                <text>助餐补贴</text>
                <view class="flex" @click="refMealSupplementsPopup.open({ autoClose: false, title: '选择餐补' })">
                  <text class="font-bold text-blue-500 price-txt">{{ useMealSupplementsInfo || "0.00" }}</text>
                  <u-icon name="arrow-right" bold color="#478af7"></u-icon
                ></view>
              </view>
              <view class="show-total-price" v-if="['card', 'face', ''].includes(currType)">
                <text>会员折扣</text>
                <text class="font-bold">{{
                  calcInfo.memberDiscount?.discount ? (100 - calcInfo.memberDiscount?.discount) / 10 + "折" : "无"
                }}</text>
              </view>
            </template>

            <template v-if="cardInfo.membershipCardType == 2">
              <view class="show-total-price">
                <text>适用餐别</text>
                <text class="font-bold">{{ splitStrToArray(accountInfo.mealTypeName).join("/") || "-" }}</text>
              </view>

              <view class="show-total-price">
                <text>套餐余额</text>
                <text class="font-bold">{{ accountInfo.surplusMealNum || "0" }}次</text>
              </view>
            </template>
          </view>

          <view v-if="pageStatus.loading">
            <text class="tips-text">{{ pageStatus.tipsText }}</text>
          </view>

          <view v-else class="w-full text-center">
            <text class="pay-type-txt block mb-10rpx">选择支付方式</text>
            <view class="flex-col w-full mt-10rpx mb-20rpx" v-if="!pageStatus.loading">
              <view
                v-for="(item, index) in payTypes"
                :key="item.value"
                @click="payTypeChange(item)"
                :class="['pay-type-item', currType == item.value ? 'active' : '']"
              >
                <view class="flex items-center">
                  <text :class="['iconzhucan', item.icon]"></text>
                  <text>{{ item.name }}</text>
                </view>
                <u-icon name="arrow-right"></u-icon>
              </view>
            </view>
          </view>
        </view>
      </u-col>
      <u-col span="4">
        <view class="col-layout pay-box" v-if="currType">
          <!-- 对应支付页 -->
          <facePay
            v-if="currType === 'face'"
            :mealSupplementPushToNext="mealSupplementPushToNext"
            :modelMoney="info.money"
          ></facePay>
          <merberPay
            v-else-if="currType === 'card'"
            :="cardInfo"
            :mealSupplementPushToNext="mealSupplementPushToNext"
          ></merberPay>
          <cashPay v-else-if="currType === 'cash'" :modelMoney="info.money" :skipPayment="false"></cashPay>
          <scanPay v-else-if="currType === 'scan'"></scanPay>
        </view>
      </u-col>
    </u-row>

    <!-- 餐补弹窗  -->
    <resultPopup ref="refMealSupplementsPopup" :show-icon="false">
      <template #default>
        <u-checkbox-group @change="checkboxChange" v-model="useMealSupplements">
          <view class="flex flex-col justify-center bg-blue-50 p-10rpx w-300rpx">
            <view class="flex items-center text-base py-8rpx" v-for="(item, index) in mealSupplements" :key="index">
              <view class="text-orange-500 font-bold text-lg"> {{ item.everydaySupplementMoney }} 元 </view>
              <view class="flex flex-col justify-start items-start flex-auto px-15rpx">
                <text class="font-bold block py-5rpx">{{ item.name }} </text>
                <view>
                  <text>{{ canUserMealType(item) }} </text>
                  <text class="text-slate-500">{{ item.superpositionUseFlag == true ? "可叠加" : "不可叠加" }} </text>
                </view>
              </view>
              <view>
                <u-checkbox
                  :disabled="item.orderUseFlag || !canUseWeekend(item)"
                  :name="item.materialRecipeLevelId"
                  size="15rpx"
                  active-color="var(--kui-color-theme)"
                >
                </u-checkbox>
              </view>
            </view>
            <view v-if="mealSupplements.length == 0" class="w-full mt-20rpx">
              <u-empty mode="data" text=" " :icon="'/static/images/state/state_no_list.png'"></u-empty>
            </view>
          </view>
        </u-checkbox-group>
      </template>
      <template #confirm="{ config }">
        <view v-if="pageStatus.errText" class="err-box">
          <text class="tips-text error">{{ pageStatus.errText }}</text>
        </view>
        <view class="btns flex">
          <view class="btns-item" @click="clearMealSupplements">
            <text class="btns-item-txt"> 关闭 </text>
          </view>
          <view :class="['btns-item', 'confirm', pageStatus.errText ? 'disabled' : '']" @click="confirmMealSupplements">
            <text class="btns-item-txt"> 确定 </text>
          </view>
        </view>
      </template>
    </resultPopup>
  </view>
</template>
<script setup>
import { onBeforeUnmount, onMounted, reactive, ref, provide, computed } from "vue";
import { useStore } from "vuex";
// 支付类型组件
import cashPay from "./cash-pay.vue";
import merberPay from "./merber-pay.vue";
import scanPay from "./scan-pay.vue";
import facePay from "./face-pay.vue";
import {
  accountInfoByCustomerId,
  calculateOrderAmount,
  getCardByCustomerId,
  listRecordById,
} from "@/api";
import resultPopup from "@/components/common-popup/result-popup.vue";
import dayjs from "dayjs";
import { initMealRules, getCurrentMealType } from "./mealTypeRulesUtils";
import { calcPayType } from "./payUtils";
import { splitStrToArray } from "@/utils/util";
import { openSubScreenByParams } from "@/utils/sceeenUtils";

const canUseWeekend = computed(() => {
  const now = dayjs().day(); 
  const isWeekend = now == "0" || now == "6";
  return (item) => {
    return isWeekend && !item.weekUseFlag;
  };
});

const store = useStore();
const show = ref(false);

const cartList = ref(store.getters.shoppingCart);

const pageStatus = reactive({
  loading: true,
  tipsText: "正在计算订单金额...",
  errText: "",
});

const payTypes = ref([
  {
    name: "会员支付",
    icon: "iconzhucan-huiyuanka",
    value: "card",
  },
  {
    name: "扫码盒子",
    icon: "iconzhucan-saomazhifu",
    value: "scan",
  },
  {
    name: "现金支付",
    icon: "iconzhucan-a-zhifufangshixianjinzhifu",
    value: "cash",
  },
  // {
  //   name: "会员人脸",
  //   icon: "iconzhucan-renlianshibie",
  //   value: "face",
  // },
]);

// 如果当前模式为无鉴权模式，则不显示 现金支付
const currMode = store.getters.consumptionPattern;
if (currMode == 3) {
  payTypes.value = payTypes.value.filter((item) => item.value !== "cash");
}

// 默认选择会员支付
const currType = ref("card");

const info = reactive({
  // 总金额（计算优惠前 - 消费金额）
  total: 0,
  // 实收金额（计算优惠后 - 实收金额）
  money: "",
  // 支付方式
  payType: "", // payType.value
});

// 支付方式变更
const payTypeChange = (item) => {
  currType.value = item.value;
  info.payType = item.value;
  console.log("payTypeChange", item, info);

  // 其他待支付商品信息
  const productDetails = store.getters.currShoppingCardInfo;
  // 如果 已经登录会员 但 支付方式为非 会员卡/人脸 这类余额支付， 不享受优惠，需显示订单实际金额 (未选择时也显示优惠后的金额)
  if (item.value !== "card" && item.value !== "face" && item.value !== "") {
    info.money = info.total;
    uni.showToast({ title: "非会员余额支付不享受优惠", icon: "none" });
  } else if (productDetails.useMember) {
    // 计算订单金额
    refreshAmount(productDetails);
  }
  // 更新客户屏
  openSubScreenByParams({ mode: "standby-mode", money: info.money, action: "please-pay", payType: item.value });
};

// 取消支付
const emitCancel = () => {
  show.value = false;
  /**
   * 支付完成事件
   *  - 包含 取消/成功/失败
   */
  emits("finish", { status: "cancel" });
};

onMounted(async () => {
  // 监听结束收款
  uni.$on("pay:finish", (payload) => {
    emits("finish", {
      ...payload,
    });
  });
});

onBeforeUnmount(() => {
  uni.$off("pay:finish");
});

const emits = defineEmits(["finish"]);

onBeforeUnmount(() => {});

const close = () => (show.value = false);
const open = async ({ cartlist, totalPrice, isPack }) => {
  info.total = totalPrice;
  cartList.value = cartlist;
  show.value = true;

  // 其他待支付商品信息
  const productDetails = store.getters.currShoppingCardInfo;
  //
  memberInfo.value = productDetails.member;

  // 如果未登录会员，直接计算价格
  if (!productDetails.useMember) {
    info.money = info.total;
    pageStatus.loading = false;
    return;
  }

  try {
    // 查询餐别
    await initMealRules();
  } catch (error) {
    console.error("查询餐别失败 > 但不要阻止下单 >", error);
  }

  // 计算订单金额
  refreshAmount(productDetails);
};

defineExpose({ close, open });

// 刷新待支付金额 （api 计算）
const calcInfo = ref({});
const refreshAmount = async (productDetails, showError = false) => {
  pageStatus.loading = true;
  pageStatus.tipsText = "正在计算订单金额...";
  pageStatus.errText = "";

  // 查询会员卡的信息 （卡类型，如果是套餐卡 显示套餐次数等）
  await initCardByInfo(productDetails.member.customerInformationId);
  await initAccountInfo(productDetails.member.customerInformationId);

  // 套餐卡特殊处理
  if (cardInfo.value.membershipCardType == 2) {
   /* noting */
  } else if (cardInfo.value.membershipCardType == 1) {
    // 会员卡特殊处理 - 查询餐补
    initMealSupplements();
  }

  try {
    // 商家信息
    const { businessId, businessName } = store.getters.businessInfo;
    // 订单列表
    const orderItems = productDetails.productList.map((v) => {
      return {
        foodName: v.name,
        foodNum: v.count,
        price: v.price,
        orderPackageItemId: v.foodTypeId,
        buffetOrderItemId: v.foodTypeId,
      };
    });
    const pam = {
      buffetOrderItemEntityList: orderItems /*  productDetails.productList */,
      payType: calcPayType(),
      businessId,
      diningStyle: productDetails.isPack ? 3 : 2,
      knCustomerInformationId: productDetails.member.customerInformationId,
      knBusinessName: businessName,
      orderType: 1, // 	订单类型（1自选订单2周期订单3日照点餐订单）
      // mealAllowance: "", //补贴金额（餐补金额）
      mealSupplementId: useMealSupplements.value.join(",") || "", // 	餐补名称id(多个逗号隔开)
      mealtype: getCurrentMealType(), // 餐别、餐次（1早餐2午餐3晚餐4下午茶5宵夜）
      // membershipLevel: "", //会员等级id
      isUse: useMealSupplements.value.length > 0 ? 1 : 2, //是否使用餐补(1是2否)
    };
    const { data } = await calculateOrderAmount(pam);
    // 根据计算的金额更新信息
    info.total = data.orderMoney;
    info.money = data.payMoney;
    pageStatus.loading = false;
    calcInfo.value = data;

    openSubScreenByParams({
      mode: "standby-mode",
      money: info.money,
      action: "please-pay",
      payType: info.value,
      detaileInfo: {
        mealAllowance: useMealSupplementsInfo.value || 0,
        memberDiscount: calcInfo.value.memberDiscount?.discount || 0,
        packageBalance: accountInfo.value.surplusMealNum,
      },
    });
  } catch (error) {
    // 失败则使用默认金额，并提示
    info.money = info.total;
    pageStatus.loading = false;
    console.warn("会员金额计算失败", error);
    pageStatus.errText = error.message;
    if (showError && error.message) uni.showToast({ title: error.message, icon: "none" });
  }
};

const memberInfo = ref({});
const cardInfo = ref({});
const initCardByInfo = async (customerId) => {
  console.log("查询卡信息", customerId);
  try {
    const { data } = await getCardByCustomerId({ customerId });
    if (data) cardInfo.value = data;
  } catch (error) {
    console.error("查询卡信息失败", error);
    // 不再抛出异常
  }
};

const accountInfo = ref({});
const initAccountInfo = async (customerId) => {
  const { businessId } = store.getters.businessInfo;
  try {
    const { data } = await accountInfoByCustomerId({ customerId, accountType: "1", businessId });
    if (data) accountInfo.value = data;
  } catch (error) {
    console.error("查询账户信息失败", error);
    // 不再抛出异常
  }
};

// 可用餐别(只输出当前餐补可用的餐别即可，无需根据当前餐别判断是否可用)
const canUserMealType = computed(() => {
  /**
   * mealType-可用餐别(1不限3限制餐别及金额)
     breakfastLimit-早餐限制金额。0或者null即表示未勾选，大于0表示早餐可
     lunchLimit-午餐限制金额。0或者null即表示未勾选，大于0表示午餐可用
     dinnerLimit-晚餐限制金额。0或者null即表示未勾选，大于0表示晚餐可用
   */
  // 根据
  return (item) => {
    const mealValues = [item.breakfastLimit, item.lunchLimit, item.dinnerLimit];
    const mealText = ["早餐", "午餐", "晚餐"];
    const useMealSupplements = [];
    for (let i = 0; i < mealValues.length; i++) {
      if (mealValues[i]) useMealSupplements.push(mealText[i]);
    }
    return useMealSupplements.join("丶");
  };
});

// 初始化餐补
const mealSupplements = ref([]);

// 餐补选择弹窗
const refMealSupplementsPopup = ref();
const initMealSupplements = async () => {
  try {
    const { businessId } = store.getters.businessInfo;
    const pam = { userId: cardInfo.value.customerInformationId, businessId };
    const { data } = await listRecordById(pam);
    mealSupplements.value = data;
  } catch (error) {
    console.error("查询用户餐补失败", error);
  }
};

const mealSupplementPushToNext = ref([]);

const confirmMealSupplements = () => {
  // 有错误的情况下不能选
  if (pageStatus.errText) return;
  refMealSupplementsPopup.value.close();
  mealSupplementPushToNext.value = mealSupplements.value.filter((v) =>
    useMealSupplements.value.includes(v.materialRecipeLevelId)
  );
};

// 取消选择
const clearMealSupplements = () => {
  refMealSupplementsPopup.value.close();
  useMealSupplements.value = [];
};

// 已选中的餐补（id）
const useMealSupplements = ref([]);
// 合计已选择餐补价格 preferentialAmount
const useMealSupplementsInfo = computed(() => {
  return mealSupplements.value
    .filter((v) => useMealSupplements.value.includes(v.materialRecipeLevelId))
    .reduce((a, b) => a + Number(b.preferentialAmount), 0);
});

const checkboxChange = (e) => {
  useMealSupplements.value = e;
  // 重新计算金额
  const productDetails = store.getters.currShoppingCardInfo;
  refreshAmount(productDetails, /* showError: */ false);
};
</script>
<style lang="scss" scoped>
.com-order-dialog {
  min-height: 60vh;
  height: 100%;
  box-sizing: border-box;
  font-size: 12rpx;
  border-radius: 5rpx;
  align-self: flex-start;

  .err-box {
    max-width: 250rpx;
    margin-bottom: 10px;
  }

  .tips-text {
    color: grey;
    font-size: 10rpx;
    display: block;
    padding: 10rpx;

    &.error {
      color: red;
      font-size: 9rpx;
    }
  }

  .col-layout {
    background-color: white;
    box-shadow: 2rpx 2rpx 5rpx #ccc;
    border-radius: 5rpx;
    min-height: 70vh;
    margin-right: 5rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 100%;
    box-sizing: border-box;

    &.pay-box {
      width: calc(100% - 10rpx);
    }

    .close {
      padding: 10rpx;
      justify-self: end;
      align-self: flex-end;
    }

    .merber-info-list {
      width: 80%;
      display: flex;
      flex-direction: column;

      .show-total-price {
        font-size: 10rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 20rpx;

        .price-txt {
          font-size: 11rpx;
        }
        .price-txt::before {
          content: "￥";
          font-size: 11rpx;
        }
      }
    }

    .title {
      font-weight: bold;
      margin-bottom: 5rpx;
    }

    .pay-type-txt {
      font-size: 10rpx;
      color: #999;
    }

    .price-txt {
      font-size: 30rpx;
      font-weight: bold;
      &::before {
        content: "￥";
        font-size: 16rpx;
        font-weight: normal;
      }
    }

    .pay-type-item {
      display: flex;
      justify-content: space-between;
      padding: 8rpx 10rpx;
      align-items: center;

      &.active {
        background-color: var(--kui-color-theme-light);
      }

      .iconzhucan {
        font-size: 15rpx;
        margin-right: 10rpx;
      }
    }
  }
}

.btns-item {
  background-color: #efefef;
  padding: 5rpx 20rpx;
  border-radius: 5rpx;
  margin: 0rpx 15rpx;
  font-size: 12rpx;

  &.disabled {
    background-color: var(--kui-color-theme-light) !important;
  }

  &.confirm {
    color: white;
    background-color: var(--kui-color-theme);
  }

  .btns-item-txt {
    font-size: 10rpx;
    padding: 5rpx 15rpx;
  }

  ::v-deep .u-button {
    padding: 2rpx 20rpx;
  }
}
</style>
